<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from 'element-plus'
import { postNotice, editNotice } from "@/api/notice.ts"
import { ElMessage } from "element-plus";

const dialogTableVisible = ref(false)
const ruleFormRef = ref()
const typeRef = ref(0)
const id = ref()
const noticeForm = reactive({
  title: '',
  content: '',
  endDate: ''
})
const emit = defineEmits<{
  'get': any
}>()

// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 初始化
const init = (number: number, row: any) => {
  if (number !== 0) {
    typeRef.value = number
    noticeForm.title = row.title
    noticeForm.content = row.content
    noticeForm.endDate = row.endDate
    id.value = row._id
  }else {
    typeRef.value = 0
    noticeForm.title = ''
    noticeForm.content = ''
    noticeForm.endDate = ''
    id.value = ''
  }
  dialogTableVisible.value = true
}

// 取消
const handleCancel = () => {
  dialogTableVisible.value = false
  resetForm(ruleFormRef.value)
}

// 确认
const handleCommit = async () => {
  const res: any = await postNotice(noticeForm)
  ElMessage({
    type: res.code === 0 ? 'success' : 'error',
    message: res.message
  })
  handleCancel()
  emit('get')
}

// 修改
const handleChange = async () => {
  const res: any = await editNotice(id.value, noticeForm)
  ElMessage({
    type: res.code === 0 ? 'success' : 'error',
    message: res.message
  })
  handleCancel()
  emit('get')
}

defineExpose({
  init
})
</script>

<template>
  <el-dialog width="40%" v-model="dialogTableVisible" :title="typeRef === 0 ? '添加公告' : '编辑公告'">
    <div class="row align_center">
      <el-form label-width="120px" v-model="noticeForm" style="width: 100%;" ref="ruleFormRef">
        <el-form-item prop="title" label="请输入标题">
          <el-input v-model="noticeForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item prop="content" label="请输入公告内容">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            resize="none"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="快写下公告内容吧"
          />
        </el-form-item>
        <el-form-item prop="title" label="请选择结束时间">
          <el-date-picker
            type="date"
            v-model="noticeForm.endDate"
            placeholder="请选择结束时间"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" v-if="typeRef === 0" @click="handleCommit">
          确认
        </el-button>
        <el-button type="primary" v-else @click="handleChange">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
